# -*- coding: utf-8
from django.db.models import *
from django.core.files.images import ImageFile
from os import path
import re, tempfile
from tbsentences import Sentence
from warnings import warn



class TreeNode(Model):
    sibling_index = IntegerField()
    nodeName =  CharField(max_length=128) 
    data = CharField(max_length=1024, blank=True)
    function = CharField(max_length=128, blank=True)
    parent = ForeignKey('TreeNode', blank=True, null=True)

    def children(self):
        return self.treenode_set.order_by("sibling_index")
    
    def words(self):
        if self.is_word():
            return [self.wordtreenode]
        words = []
        for c in self.children():
            words += c.words()
        return words
    
    def sentence(self):
        if self.parent:
            return self.parent.sentence()
        else:
            return Sentence.objects.get(tree=self)
    
    def attributes(self):
        return map(lambda x: x.key, self.nodeattribute_set.all())
    
        
    def getattr(self, key, default=None):
        try:
            return self.nodeattribute_set.get(node=self, key=key).value
        except NodeAttribute.DoesNotExist:
            return default
    
    def setattr(self, key, value):
        try:
            attr = NodeAttribute.objects.get(node=self, key=key)
            attr.value = value
            attr.save()
        except NodeAttribute.DoesNotExist:
            attr = NodeAttribute(node=self, key=key, value=value)
            attr.save()
            
    def get_text(self):
        if self.is_text_node():
            return self.data
        else:
            return u" ".join(map(lambda x: x.get_text(), self.children()))
            
    def is_text_node(self):
        return self.nodeName == "#text"
        
    def is_word(self):
        return hasattr(self, "wordtreenode")
        
    def word(self):
        return self.wordtreenode
    
    def __unicode__(self):
        if self.nodeName == "#text":
            return u"« %s »" % self.data
        else:
            return self.nodeName
    
    class Meta:
        app_label = 'core'


class WordTreeNode(TreeNode):
    #index = IntegerField()
    #sentence = ForeignKey('Sentence')
    form = CharField(max_length=1024)
    lemma = CharField(max_length=1024)
    cat = CharField(max_length=128)
    ee = CharField(max_length=128)
    ei = CharField(max_length=128)
    mph = CharField(max_length=128)
    subcat = CharField(max_length=128)
    
    def __unicode__(self):
        return self.form
    

    class Meta:
        app_label = 'core'

class NodeAttribute(Model):
    node = ForeignKey('TreeNode')
    key = CharField(max_length=255)
    value = CharField(max_length=255)

    class Meta:
        app_label = 'core'

